import React, { useState, useEffect, useCallback } from 'react';
import { 
  Card, 
  Row, 
  Col, 
  Statistic, 
  Progress, 
  Table, 
  Tag, 
  Space,
  Button,
  Alert,
  Typography,
  Tabs,
  Select,
  Switch
} from 'antd';
import { 
  DashboardOutlined, 
  ThunderboltOutlined, 
  ClockCircleOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ReloadOutlined,
  TrophyOutlined
} from '@ant-design/icons';
import { 
  LineChart, 
  Line, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer,
  AreaChart,
  Area
} from 'recharts';

const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { Option } = Select;

interface PerformanceMetric {
  id: string;
  name: string;
  value: number;
  unit: string;
  status: 'excellent' | 'good' | 'warning' | 'critical';
  threshold: {
    excellent: number;
    good: number;
    warning: number;
  };
  lastUpdated: string;
}

interface ApiEndpointMetric {
  endpoint: string;
  method: string;
  avgResponseTime: number;
  requestCount: number;
  errorRate: number;
  lastAccessed: string;
  status: 'healthy' | 'degraded' | 'unhealthy';
}

interface SystemHealthMetric {
  component: string;
  status: 'up' | 'down' | 'degraded';
  responseTime?: number;
  errorCount: number;
  lastCheck: string;
  message?: string;
}

const EnhancedPerformanceDashboard: React.FC = () => {
  const [performanceMetrics, setPerformanceMetrics] = useState<PerformanceMetric[]>([]);
  const [apiMetrics, setApiMetrics] = useState<ApiEndpointMetric[]>([]);
  const [systemHealth, setSystemHealth] = useState<SystemHealthMetric[]>([]);
  const [performanceHistory, setPerformanceHistory] = useState<any[]>([]);
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [refreshInterval, setRefreshInterval] = useState(10);
  const [loading, setLoading] = useState(false);

  // 模拟性能数据
  const generateMockData = useCallback(() => {
    const now = new Date();
    
    const metrics: PerformanceMetric[] = [
      {
        id: 'response-time',
        name: 'API响应时间',
        value: Math.random() * 100 + 50,
        unit: 'ms',
        status: Math.random() > 0.7 ? 'warning' : 'good',
        threshold: { excellent: 50, good: 100, warning: 200 },
        lastUpdated: now.toISOString()
      },
      {
        id: 'memory-usage',
        name: '内存使用率',
        value: Math.random() * 30 + 60,
        unit: '%',
        status: Math.random() > 0.8 ? 'warning' : 'good',
        threshold: { excellent: 70, good: 80, warning: 90 },
        lastUpdated: now.toISOString()
      },
      {
        id: 'cpu-usage',
        name: 'CPU使用率',
        value: Math.random() * 20 + 40,
        unit: '%',
        status: 'good',
        threshold: { excellent: 50, good: 70, warning: 85 },
        lastUpdated: now.toISOString()
      },
      {
        id: 'request-rate',
        name: '请求频率',
        value: Math.random() * 50 + 100,
        unit: 'req/min',
        status: 'excellent',
        threshold: { excellent: 200, good: 150, warning: 100 },
        lastUpdated: now.toISOString()
      }
    ];

    const apis: ApiEndpointMetric[] = [
      {
        endpoint: '/api/weather',
        method: 'GET',
        avgResponseTime: Math.random() * 50 + 30,
        requestCount: Math.floor(Math.random() * 1000 + 500),
        errorRate: Math.random() * 2,
        lastAccessed: now.toISOString(),
        status: 'healthy'
      },
      {
        endpoint: '/api/weather/cities',
        method: 'GET',
        avgResponseTime: Math.random() * 30 + 20,
        requestCount: Math.floor(Math.random() * 200 + 100),
        errorRate: Math.random() * 1,
        lastAccessed: now.toISOString(),
        status: 'healthy'
      },
      {
        endpoint: '/api/statistics/overview',
        method: 'GET',
        avgResponseTime: Math.random() * 100 + 80,
        requestCount: Math.floor(Math.random() * 100 + 50),
        errorRate: Math.random() * 3,
        lastAccessed: now.toISOString(),
        status: Math.random() > 0.8 ? 'degraded' : 'healthy'
      }
    ];

    const health: SystemHealthMetric[] = [
      {
        component: '数据库连接',
        status: 'up',
        responseTime: Math.random() * 10 + 5,
        errorCount: 0,
        lastCheck: now.toISOString()
      },
      {
        component: 'SignalR Hub',
        status: Math.random() > 0.9 ? 'degraded' : 'up',
        responseTime: Math.random() * 20 + 10,
        errorCount: Math.floor(Math.random() * 3),
        lastCheck: now.toISOString()
      },
      {
        component: '缓存服务',
        status: 'up',
        responseTime: Math.random() * 5 + 2,
        errorCount: 0,
        lastCheck: now.toISOString()
      },
      {
        component: '后台作业',
        status: Math.random() > 0.95 ? 'down' : 'up',
        errorCount: Math.floor(Math.random() * 2),
        lastCheck: now.toISOString(),
        message: '数据采集作业运行正常'
      }
    ];

    setPerformanceMetrics(metrics);
    setApiMetrics(apis);
    setSystemHealth(health);

    // 添加历史数据点
    setPerformanceHistory(prev => {
      const newPoint = {
        time: now.toLocaleTimeString(),
        responseTime: metrics[0].value,
        memoryUsage: metrics[1].value,
        cpuUsage: metrics[2].value,
        requestRate: metrics[3].value
      };
      return [...prev.slice(-19), newPoint]; // 保持最近20个数据点
    });
  }, []);

  // 自动刷新
  useEffect(() => {
    if (autoRefresh) {
      const interval = setInterval(generateMockData, refreshInterval * 1000);
      return () => clearInterval(interval);
    }
  }, [autoRefresh, refreshInterval, generateMockData]);

  // 初始加载
  useEffect(() => {
    generateMockData();
  }, [generateMockData]);

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'excellent':
      case 'up':
      case 'healthy':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'good':
      case 'degraded':
        return <WarningOutlined style={{ color: '#faad14' }} />;
      case 'warning':
        return <WarningOutlined style={{ color: '#fa8c16' }} />;
      case 'critical':
      case 'down':
      case 'unhealthy':
        return <WarningOutlined style={{ color: '#f5222d' }} />;
      default:
        return <ClockCircleOutlined />;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'excellent':
      case 'up':
      case 'healthy':
        return 'success';
      case 'good':
      case 'degraded':
        return 'warning';
      case 'warning':
        return 'orange';
      case 'critical':
      case 'down':
      case 'unhealthy':
        return 'error';
      default:
        return 'default';
    }
  };

  const getProgressStatus = (metric: PerformanceMetric) => {
    if (metric.value <= metric.threshold.excellent) return 'success';
    if (metric.value <= metric.threshold.good) return 'normal';
    if (metric.value <= metric.threshold.warning) return 'exception';
    return 'exception';
  };

  const apiColumns = [
    {
      title: 'API端点',
      dataIndex: 'endpoint',
      key: 'endpoint',
      render: (endpoint: string, record: ApiEndpointMetric) => (
        <Space>
          <Tag color={record.method === 'GET' ? 'blue' : record.method === 'POST' ? 'green' : 'orange'}>
            {record.method}
          </Tag>
          <code>{endpoint}</code>
        </Space>
      )
    },
    {
      title: '平均响应时间',
      dataIndex: 'avgResponseTime',
      key: 'avgResponseTime',
      render: (time: number) => `${time.toFixed(1)}ms`,
      sorter: (a, b) => a.avgResponseTime - b.avgResponseTime
    },
    {
      title: '请求次数',
      dataIndex: 'requestCount',
      key: 'requestCount',
      render: (count: number) => count.toLocaleString(),
      sorter: (a, b) => a.requestCount - b.requestCount
    },
    {
      title: '错误率',
      dataIndex: 'errorRate',
      key: 'errorRate',
      render: (rate: number) => (
        <Tag color={rate > 5 ? 'red' : rate > 2 ? 'orange' : 'green'}>
          {rate.toFixed(2)}%
        </Tag>
      ),
      sorter: (a, b) => a.errorRate - b.errorRate
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Space>
          {getStatusIcon(status)}
          <Tag color={getStatusColor(status)}>
            {status.toUpperCase()}
          </Tag>
        </Space>
      )
    }
  ];

  const healthColumns = [
    {
      title: '组件',
      dataIndex: 'component',
      key: 'component'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Space>
          {getStatusIcon(status)}
          <Tag color={getStatusColor(status)}>
            {status.toUpperCase()}
          </Tag>
        </Space>
      )
    },
    {
      title: '响应时间',
      dataIndex: 'responseTime',
      key: 'responseTime',
      render: (time?: number) => time ? `${time.toFixed(1)}ms` : '-'
    },
    {
      title: '错误计数',
      dataIndex: 'errorCount',
      key: 'errorCount',
      render: (count: number) => (
        <Tag color={count > 0 ? 'red' : 'green'}>
          {count}
        </Tag>
      )
    },
    {
      title: '最后检查',
      dataIndex: 'lastCheck',
      key: 'lastCheck',
      render: (time: string) => new Date(time).toLocaleTimeString()
    },
    {
      title: '备注',
      dataIndex: 'message',
      key: 'message',
      render: (message?: string) => message || '-'
    }
  ];

  const overallHealthScore = systemHealth.filter(h => h.status === 'up').length / systemHealth.length * 100;

  return (
    <div>
      {/* 控制面板 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={24}>
          <Card size="small">
            <Space split={<span style={{ color: '#d9d9d9' }}>|</span>}>
              <Space>
                <Text>自动刷新:</Text>
                <Switch
                  checked={autoRefresh}
                  onChange={setAutoRefresh}
                  size="small"
                />
              </Space>
              <Space>
                <Text>刷新间隔:</Text>
                <Select
                  value={refreshInterval}
                  onChange={setRefreshInterval}
                  size="small"
                  style={{ width: 80 }}
                >
                  <Option value={5}>5s</Option>
                  <Option value={10}>10s</Option>
                  <Option value={30}>30s</Option>
                  <Option value={60}>60s</Option>
                </Select>
              </Space>
              <Button
                size="small"
                icon={<ReloadOutlined />}
                onClick={generateMockData}
                loading={loading}
              >
                立即刷新
              </Button>
            </Space>
          </Card>
        </Col>
      </Row>

      {/* 整体健康状况 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={24}>
          <Alert
            message={
              <Space>
                <TrophyOutlined />
                <span>系统整体健康度: {overallHealthScore.toFixed(1)}%</span>
              </Space>
            }
            description={`${systemHealth.filter(h => h.status === 'up').length}/${systemHealth.length} 个组件运行正常`}
            type={overallHealthScore >= 80 ? 'success' : overallHealthScore >= 60 ? 'warning' : 'error'}
            showIcon
          />
        </Col>
      </Row>

      <Tabs defaultActiveKey="metrics">
        <TabPane tab="性能指标" key="metrics">
          {/* 关键性能指标 */}
          <Row gutter={16} style={{ marginBottom: 16 }}>
            {performanceMetrics.map(metric => (
              <Col xs={24} sm={12} md={6} key={metric.id}>
                <Card size="small">
                  <Statistic
                    title={metric.name}
                    value={metric.value}
                    suffix={metric.unit}
                    precision={1}
                    prefix={getStatusIcon(metric.status)}
                    valueStyle={{ 
                      color: metric.status === 'excellent' ? '#52c41a' : 
                             metric.status === 'good' ? '#1890ff' :
                             metric.status === 'warning' ? '#faad14' : '#f5222d'
                    }}
                  />
                  <Progress 
                    percent={Math.min((metric.value / metric.threshold.warning) * 100, 100)}
                    status={getProgressStatus(metric)}
                    size="small"
                    style={{ marginTop: 8 }}
                  />
                </Card>
              </Col>
            ))}
          </Row>

          {/* 性能趋势图 */}
          <Card title="性能趋势图" style={{ marginBottom: 16 }}>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={performanceHistory}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis yAxisId="left" />
                <YAxis yAxisId="right" orientation="right" />
                <Tooltip />
                <Line 
                  yAxisId="left"
                  type="monotone" 
                  dataKey="responseTime" 
                  stroke="#ff7300" 
                  name="响应时间(ms)"
                  strokeWidth={2}
                />
                <Line 
                  yAxisId="right"
                  type="monotone" 
                  dataKey="memoryUsage" 
                  stroke="#00bcd4" 
                  name="内存使用率(%)"
                  strokeWidth={2}
                />
                <Line 
                  yAxisId="right"
                  type="monotone" 
                  dataKey="cpuUsage" 
                  stroke="#4caf50" 
                  name="CPU使用率(%)"
                  strokeWidth={2}
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </TabPane>

        <TabPane tab="API性能" key="api">
          <Card title="API端点性能监控">
            <Table
              columns={apiColumns}
              dataSource={apiMetrics}
              rowKey="endpoint"
              pagination={false}
              size="small"
            />
          </Card>
        </TabPane>

        <TabPane tab="系统健康" key="health">
          <Card title="系统组件健康检查">
            <Table
              columns={healthColumns}
              dataSource={systemHealth}
              rowKey="component"
              pagination={false}
              size="small"
            />
          </Card>

          {/* 资源使用图表 */}
          <Card title="资源使用趋势" style={{ marginTop: 16 }}>
            <ResponsiveContainer width="100%" height={250}>
              <AreaChart data={performanceHistory}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis />
                <Tooltip />
                <Area 
                  type="monotone" 
                  dataKey="memoryUsage" 
                  stackId="1"
                  stroke="#00bcd4" 
                  fill="#00bcd4"
                  fillOpacity={0.6}
                  name="内存使用率"
                />
                <Area 
                  type="monotone" 
                  dataKey="cpuUsage" 
                  stackId="1"
                  stroke="#4caf50" 
                  fill="#4caf50"
                  fillOpacity={0.6}
                  name="CPU使用率"
                />
              </AreaChart>
            </ResponsiveContainer>
          </Card>
        </TabPane>

        <TabPane tab="实时监控" key="realtime">
          <Row gutter={16}>
            <Col xs={24} lg={12}>
              <Card title="实时API调用" size="small">
                <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Space direction="vertical" align="center">
                    <Progress
                      type="circle"
                      percent={Math.floor(Math.random() * 100)}
                      format={() => `${Math.floor(Math.random() * 50 + 100)}/s`}
                      strokeColor={{
                        '0%': '#108ee9',
                        '100%': '#87d068',
                      }}
                    />
                    <Text>当前请求频率</Text>
                  </Space>
                </div>
              </Card>
            </Col>
            <Col xs={24} lg={12}>
              <Card title="错误率监控" size="small">
                <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Space direction="vertical" align="center">
                    <Progress
                      type="circle"
                      percent={100 - Math.floor(Math.random() * 10)}
                      format={(percent) => `${(100 - percent!).toFixed(1)}%`}
                      strokeColor={100 - Math.floor(Math.random() * 10) > 95 ? '#52c41a' : '#faad14'}
                    />
                    <Text>错误率</Text>
                  </Space>
                </div>
              </Card>
            </Col>
          </Row>

          <Card title="活跃连接" style={{ marginTop: 16 }}>
            <Row gutter={16}>
              <Col span={8}>
                <Statistic
                  title="SignalR连接数"
                  value={Math.floor(Math.random() * 50 + 20)}
                  prefix={<ThunderboltOutlined />}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="数据库连接池"
                  value={Math.floor(Math.random() * 10 + 5)}
                  suffix="/ 20"
                  prefix={<DashboardOutlined />}
                />
              </Col>
              <Col span={8}>
                <Statistic
                  title="缓存命中率"
                  value={Math.random() * 10 + 85}
                  suffix="%"
                  precision={1}
                  prefix={<TrophyOutlined />}
                  valueStyle={{ color: '#3f8600' }}
                />
              </Col>
            </Row>
          </Card>
        </TabPane>
      </Tabs>
    </div>
  );
};

export default EnhancedPerformanceDashboard;